import { app } from 'electron';
import regedit from 'regedit';
import { protocolName } from '#common/configs/registry-const';
import log from '$main/utils/logger';

export const readProtocol = (args: String[]) => {
  return args.find((arg) => arg.startsWith(`${protocolName}://`));
};

export const addToRegistry = () => {
  regedit.setExternalVBSLocation('./resources/vbs');

  const applicationPath = app.getPath('exe');
  const protocolKey = 'HKCR\\' + protocolName;

  // 检查是否已经存在注册表条目，如果不存在则创建
  regedit.list([protocolKey], (err, result) => {
    if (err) {
      log.error('Error reading registry:', err);
      return;
    }
    if (result && result[protocolKey] && result[protocolKey]['exists']) {
      console.log('Registry key exists:', result[protocolKey]);
      return;
    } else {
      log.log('Registry key does not exist.');
    }
    regedit.createKey([protocolKey, `${protocolKey}\\Shell\\Open\\Command`], (err) => {
      if (err) {
        log.error('Error creating key:', err);
        return;
      }
      log.log('Registry writing');
      regedit.putValue(
        {
          [protocolKey]: {
            'URL Protocol': { value: '', type: 'REG_SZ' }
          },
          [`${protocolKey}\\Shell\\Open\\Command`]: {
            default: { value: `"${applicationPath}"`, type: 'REG_DEFAULT' }
          }
        },
        (err) => {
          if (err) {
            log.error('Error writing to registry:', err);
          } else {
            log.log('Registry entry created successfully!');
          }
        }
      );
    });
  });
};
